﻿using ComPortClass;
using SimStatus.Core;
using SimStatus.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SimStatus
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window,SimStatus.Core.IMainPage 
    {
        private Timer timer1 = new Timer();
        NotifyIcon notifyIcon;
        ComPortClass.ComPortClass com;
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
                com = new ComPortClass.ComPortClass(this.PortName, int.Parse(this.PortNumber));
                Logs = new List<Log>();
                if (String.IsNullOrEmpty(this.DialerName))
                {
                    this.DialerName = "Di";
                    for (int i = 0; i < 10; i++)
                    {
                        this.DialerName += ran.Next(0, 9);
                    }
                }

                if (first)
                {
                    dash = new Dashboard();
                    dash.main = this;
                    var firstStep = new SimStatus.UI.Install_Checking();
                    firstStep.main = this;
                    ShowContent(firstStep);
                    dash.Show();
                    Jpp.DoEvent();
                    firstStep.Do();

                }
                else
                {
                    dash = new Dashboard();
                    dash.main = this;
                    var maindash = new MainBoard();
                    maindash.main = this;
                    dash.Content = maindash;
                    dash.Show();
                }

                timer1.Enabled = true;
                timer1.Interval = 5000;
                timer1.Tick += timer1_Tick; 
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            var csq = int.Parse(GetCSQ());
            if (csq == 0 || csq > 30)
            {
                ChangeIcon(new System.Drawing.Icon("WlanMM_0004.ico"));
            }
            else if (csq > 0 && csq <= 6)
            {
                ChangeIcon(new System.Drawing.Icon("WlanMM_0005.ico"));
            }
            else if (csq > 6 && csq <= 12)
            {
                ChangeIcon(new System.Drawing.Icon("WlanMM_0006.ico"));
            }
            else if (csq > 12 && csq <= 18)
            {
                ChangeIcon(new System.Drawing.Icon("WlanMM_0007.ico"));
            }
            else if (csq > 18 && csq<=24)
            {
                ChangeIcon(new System.Drawing.Icon("WlanMM_0008.ico"));
            }
            else if (csq > 24)
            {
                ChangeIcon(new System.Drawing.Icon("WlanMM_0009.ico"));
            }
        }

        public Dashboard dash { get; set; }

        public Core.StatusEntity Status
        {
            get;
            set;
        }

        private bool first
        { 
            get { return bool.Parse(appSetting.GetConfig("1st")); }
            set { appSetting.SetConfig("1st", value.ToString()); }
        
        }

        public string PortName
        {
            get
            {
                return appSetting.GetConfig("PortName");
            }
            set
            {
                appSetting.SetConfig("PortName", value);
            }
        }

        public string PortNumber
        {
            get
            {
                return appSetting.GetConfig("PortNumber");
            }
            set
            {
                appSetting.SetConfig("PortNumber", value);
            }
        }

        public string DialerName
        {
            get
            {
                return appSetting.GetConfig("DialerName");
            }
            set
            {
                appSetting.SetConfig("DialerName", value);
            }
        }

        public Core.ConnectResult ConnectToPort(string PortName, string PortNumber)
        {
            try
            {
                ComPortClass.ComPortClass com = new ComPortClass.ComPortClass(PortName, int.Parse(PortNumber));
                com.CloseCom();
                if (com.ATCommand("at+imei?").ToUpper().Contains("ERROR"))
                {
                    return ConnectResult.NoSim;
                }
                return ConnectResult.Connected;
            }
            catch
            {
                return ConnectResult.Error;
            }
        }

        public void InitIcon()
        {
            this.notifyIcon = new NotifyIcon();
            this.notifyIcon.BalloonTipText = "系统监控中... ...";
            this.notifyIcon.ShowBalloonTip(2000);
            this.notifyIcon.Text = "系统监控中... ...";
            this.notifyIcon.Icon = new System.Drawing.Icon(@"WlanMM_0009.ico");
            this.notifyIcon.Visible = true;
            //打开菜单项
            System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("打开窗口");
            open.Click += (obj, e) =>
            {
                var dash = new MainBoard();
                dash.main = this;
                this.ShowContent(dash);
            };
            //退出菜单项
            System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("退出");
            exit.Click += (obj, e) =>
            {
                this.Terminate();
            };
            //拨号连接
            System.Windows.Forms.MenuItem openNetwork = new System.Windows.Forms.MenuItem("开启数据网络");
            openNetwork.Click += (obj, e) =>
            {
                this.Dial();
            };
            //断开拨号连接
            System.Windows.Forms.MenuItem closeNetwork = new System.Windows.Forms.MenuItem("断开数据网络");
            closeNetwork.Click += (obj, e) =>
            {
                this.UnDial();
            };
            //关联托盘控件
            System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit, openNetwork, closeNetwork };
            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);

            this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    var dash = new MainBoard();
                    dash.main = this;
                    this.ShowContent(dash);
                }
            });
        }

        public new void ShowDialog()
        {
            dash.Show();
        }

        public void CloseDialog()
        {
            dash.Hide();
        }

        public void Terminate()
        {
            Environment.Exit(0);
        }

        public string GetCSQ()
        {
            return this.ExcuteAtCommang("at+csq?");
        }

        public string GetCops()
        {
            return this.ExcuteAtCommang("at+cops?");
        }

        public string ExcuteAtCommang(string Command)
        {
            return com.ATCommand(Command);
        }

        public String Dial()
        {
            var res = this.ExcuteCMD(String.Format("RasDial {0}", this.DialerName));
            IsDial = true;
            return res;
        }

        public bool CreateDial()
        {
            DialConnection conn = new DialConnection(this.DialerName, "*99***1#");
            var res= conn.CreateConnection();
            if (res == CreateConnectionStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void ChangeIcon(System.Drawing.Icon icon)
        {
            this.notifyIcon.Icon = icon;
        }


        public List<string> GetAllUserPhoneBook()
        {
            DialConnection conn = new DialConnection(this.DialerName, "*99***1#");
            return conn.GetAllUserPhoneBook();
        }

        public Random ran
        {
            get
            {
                return _ran;
            }
            set
            {
                _ran = value;
            }
        }
        private static Random _ran = new Random();

        public List<Log> Logs
        {
            get;
            set;
        }


        public string ExcuteCMD(string CMD)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";

            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;

            p.Start();
            p.StandardInput.WriteLine(CMD);

            p.StandardInput.WriteLine("exit");
            p.WaitForExit();
            String output = p.StandardOutput.ReadToEnd();
            p.Close();
            return output;
        }


        public bool IsDial
        {
            get;
            set;
        }


        public string UnDial()
        {
           var res= this.ExcuteCMD(String.Format("RasDial {0} /DISCONNECT", this.DialerName));
           IsDial = false;
           return res;
        }

        public void ShowContent(IContent obj)
        {
            dash.Content = obj;
        }


        public void Report(Log log)
        {
            throw new NotImplementedException();
        }

        public void Report(List<Log> logs)
        {
            throw new NotImplementedException();
        }
    }
}
